<%doc>
USAGE DOCUMENTATION :: PLEASE LEAVE THIS AT THE TOP OF THIS FILE

For Mako templating syntax documentation please visit: http://docs.makotemplates.org/en/latest/

Filename:           user.html
Version:            0.1
Variable names:     data [list]

data :: Usable parameters

user_id             Returns the user id of the user.
username            Returns the user's username.
friendly_name       Returns the friendly name of the user.
email               Returns the user's email address.
user_thumb          Returns the thumbnail for the user.
is_home_user        Returns bool value for whether the user is part of a Plex Home.
is_allow_sync       Returns bool value for whether the user has sync rights.
is_restricted       Returns bool value for whether the user account is restricted.
do_notify           Returns bool value for whether to send notifications for the user.
keep_history        Returns bool value for whether to keep history for the user.

DOCUMENTATION :: END

</%doc>

<%inherit file="base.html"/>
<%!
    from plexpy.helpers import page
%>

<%def name="headIncludes()">
<link rel="stylesheet" href="${http_root}css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="${http_root}css/dataTables.colVis.css">
<link rel="stylesheet" href="${http_root}css/tautulli-dataTables.css">
</%def>

<%def name="body()">
% if data:
<div class="container-fluid">
    <div class="row">
        <div class="summary-container">
            <div class="summary-navbar">
                <div class="col-md-12">
                    <div class="summary-navbar-list">
                        <ul class="list-unstyled breadcrumb">
                            <li class="active">${data['friendly_name']}</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="summary-content-wrapper" style="min-height: calc(100% - 50px);">
                <div class="col-md-12">
                    <div class="table-card-back">
                        <div class="user-info-wrapper">
                            <div class="user-info-poster-face" style="background-image: url(${page('pms_image_proxy', data['user_thumb'], None, 80, 80, fallback='user')});">
                                % if not data['is_active']:
                                <span class="inactive-user-tooltip" data-toggle="tooltip" title="User not on Plex server">
                                    <i class="fa fa-2x fa-exclamation-triangle"></i>
                                </span>
                                % endif
                            </div>
                            <div class="user-info-username">
                                <span class="set-username">${data['friendly_name']}</span>
                                % if _session['user_group'] == 'admin':
                                <span id="edit-user-tooltip" data-target="tooltip" title="Edit user details">
                                    <a href="#" data-toggle="modal" data-target="#edit-user-modal" id="toggle-edit-user-modal"><i class="fa fa-pencil"></i></a>
                                </span>
                                % endif
                            </div>
                            <div class="user-info-nav">
                                <ul class="nav nav-list nav-pills" role="tablist">
                                    <li class="active"><a id="nav-tabs-profile" href="#tabs-profile" role="tab" data-toggle="tab">Profile</a></li>
                                    <li><a id="nav-tabs-history" href="#tabs-history" role="tab" data-toggle="tab">History</a></li>
                                    <li><a id="nav-tabs-playlists" href="#tabs-playlists" role="tab" data-toggle="tab">Playlists</a></li>
                                    % if _session['user_group'] == 'admin':
                                    <li><a id="nav-tabs-export" href="#tabs-export" role="tab" data-toggle="tab">Export</a></li>
                                    % endif
                                    <li><a id="nav-tabs-ipaddresses" href="#tabs-ipaddresses" role="tab" data-toggle="tab">IP Addresses</a></li>
                                    <li><a id="nav-tabs-tautullilogins" href="#tabs-tautullilogins" role="tab" data-toggle="tab">Tautulli Logins</a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="tabs-profile">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="table-card-header">
                                        <div class="header-bar">
                                            <span><i class="fa fa-line-chart"></i> Global Stats</span>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <div id="user-time-stats" class="user-overview-stats-wrapper">
                                            <div class='muted'><i class="fa fa-refresh fa-spin"></i> Loading data...</div>
                                            <br>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="table-card-header">
                                        <div class="header-bar">
                                            <span><i class="fa fa-television"></i> Player Stats</span>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <div id="user-player-stats" class="user-player">
                                            <div class='muted'><i class="fa fa-refresh fa-spin"></i> Loading data...</div>
                                            <br>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="table-card-header">
                                        <ul class="nav nav-header nav-dashboard pull-right">
                                            <li>
                                                <a href="#" id="recently-watched-page-left" class="paginate-watched btn-gray disabled" data-id="-1"><i class="fa fa-lg fa-chevron-left"></i></a>
                                            </li>
                                            <li>
                                                <a href="#" id="recently-watched-page-right" class="paginate-watched btn-gray" data-id="+1"><i class="fa fa-lg fa-chevron-right"></i></a>
                                            </li>
                                        </ul>
                                        <div class="header-bar">
                                            <span><i class="fa fa-history"></i> Recently Played</span>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <div id="user-recently-watched">
                                            <div class='muted'><i class="fa fa-refresh fa-spin"></i> Loading data...</div>
                                            <br>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="tabs-history">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class='table-card-header'>
                                        <div class="header-bar">
                                            <span>
                                                <i class="fa fa-history"></i> History for <strong>
                                                    <span class="set-username">${data['friendly_name']}</span>
                                                </strong>
                                            </span>
                                        </div>
                                        <div class="button-bar">
                                            % if _session['user_group'] == 'admin':
                                            <div class="btn-group">
                                                <button class="btn btn-danger btn-edit" data-toggle="button" aria-pressed="false" autocomplete="off" id="row-edit-mode">
                                                    <i class="fa fa-trash-o"></i> Delete mode
                                                </button>
                                            </div>
                                            % endif
                                            <div class="btn-group" data-toggle="buttons" id="media_type-selection">
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="media_type-filter" id="history-media_type-movie" value="movie" autocomplete="off"><i class="fa fa-film"></i> Movies
                                                </label>
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="media_type-filter" id="history-media_type-episode" value="episode" autocomplete="off"><i class="fa fa-television"></i> TV Shows
                                                </label>
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="media_type-filter" id="history-media_type-track" value="track" autocomplete="off"><i class="fa fa-music"></i> Music
                                                </label>
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="media_type-filter" id="history-media_type-live" value="live" autocomplete="off"><i class="fa fa-broadcast-tower"></i> Live TV
                                                </label>
                                            </div>
                                            <div class="btn-group" data-toggle="buttons" id="transcode_decision-selection">
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="transcode_decision-filter" id="history-transcode_decision-direct_play" value="direct play" autocomplete="off"><i class="fa fa-play-circle"></i> Direct Play
                                                </label>
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="transcode_decision-filter" id="history-transcode_decision-direct_stream" value="copy" autocomplete="off"><i class="fa fa-stream"></i> Direct Stream
                                                </label>
                                                <label class="btn btn-dark btn-filter">
                                                    <input type="checkbox" name="transcode_decision-filter" id="history-transcode_decision-transcode" value="transcode" autocomplete="off"><i class="fa fa-server"></i> Transcode
                                                </label>
                                            </div>
                                            <div class="btn-group">
                                                <button class="btn btn-dark refresh-history-button" id="refresh-history-list"><i class="fa fa-refresh"></i> Refresh history</button>
                                            </div>
                                            <div class="btn-group colvis-button-bar" id="button-bar-history"></div>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <table class="display history_table" id="history_table-UID-${data['user_id']}" width="100%">
                                            <thead>
                                                <tr>
                                                    <th align="left" id="delete">Delete</th>
                                                    <th align="left" id="date">Date</th>
                                                    <th align="left" id="friendly_name">User</th>
                                                    <th align="left" id="ip_address">IP Address</th>
                                                    <th align="left" id="platform">Platform</th>
                                                    <th align="left" id="product">Product</th>
                                                    <th align="left" id="player">Player</th>
                                                    <th align="left" id="title">Title</th>
                                                    <th align="left" id="started">Started</th>
                                                    <th align="left" id="paused_counter">Paused</th>
                                                    <th align="left" id="stopped">Stopped</th>
                                                    <th align="left" id="play_duration">Duration</th>
                                                    <th align="left" id="percent_complete"></th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="tabs-playlists">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class='table-card-header'>
                                        <div class="header-bar">
                                            <span>
                                                <i class="fa fa-list-alt"></i> Playlists for <strong>
                                                    <span class="set-username">${data['friendly_name']}</span>
                                                </strong>
                                            </span>
                                        </div>
                                        <div class="button-bar">
                                            % if _session['user_group'] == 'admin':
                                            <div class="btn-group">
                                                <button class="btn btn-dark export-button" id="toggle-export-modal" data-toggle="modal" data-target="#export-modal"
                                                        data-user_id="${data['user_id']}" data-media_type="playlist" data-sub_media_type="video,audio,photo"
                                                        data-export_type="playlist">
                                                    <i class="fa fa-file-export"></i> Export playlists
                                                </button>
                                            </div>
                                            % endif
                                            <div class="btn-group">
                                                <button class="btn btn-dark refresh-playlists-table-button" id="refresh-playlists-table">
                                                    <i class="fa fa-refresh"></i> Refresh playlists
                                                </button>
                                            </div>
                                            <div class="btn-group colvis-button-bar" id="button-bar-playlists"></div>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <table class="display playlists_table" id="playlists_table-SID-${data['user_id']}" width="100%">
                                            <thead>
                                                <tr>
                                                    <th align="left" id="playlistTitle">Playlist Title</th>
                                                    <th align="left" id="playlistLeafCount">Playlist Items</th>
                                                    <th align="left" id="playlistDuration">Playlist Duration</th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    % if _session['user_group'] == 'admin':
                    <div role="tabpanel" class="tab-pane" id="tabs-export">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class='table-card-header'>
                                        <div class="header-bar">
                                            <span>
                                                <i class="fa fa-file-export"></i> Metadata Exports for <strong>
                                                    <span class="set-username">${data['friendly_name']}</span>
                                                </strong>
                                            </span>
                                        </div>
                                        <div class="button-bar">
                                            <div class="btn-group">
                                                <button class="btn btn-dark refresh-export-table-button" id="refresh-export-table">
                                                    <i class="fa fa-refresh"></i> Refresh exports
                                                </button>
                                            </div>
                                            <div class="btn-group colvis-button-bar" id="button-bar-export"></div>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <table class="display export_table" id="export_table-SID-${data['user_id']}" width="100%">
                                            <thead>
                                                <tr>
                                                    <th align="left" id="timestamp">Exported At</th>
                                                    <th align="left" id="media_type_title">Media Type</th>
                                                    <th align="left" id="rating_key">Rating Key</th>
                                                    <th align="left" id="filename">Filename</th>
                                                    <th align="left" id="file_format">File Format</th>
                                                    <th align="left" id="metadata_level">Metadata Level</th>
                                                    <th align="left" id="media_info_level">Media Info Level</th>
                                                    <th align="left" id="media_info_level">Custom Fields</th>
                                                    <th align="left" id="file_size">File Size</th>
                                                    <th align="left" id="complete">Download</th>
                                                    <th align="left" id="delete">Delete</th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    % endif
                    <div role="tabpanel" class="tab-pane" id="tabs-ipaddresses">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="table-card-header">
                                        <div class="header-bar">
                                            <span>
                                                <i class="fa fa-map-marker"></i> IP Addresses for <strong>
                                                    <span class="set-username">${data['friendly_name']}</span>
                                                </strong>
                                            </span>
                                        </div>
                                        <div class="button-bar">
                                            <div class="btn-group">
                                                <button class="btn btn-dark refresh-ip-address-button" id="refresh-ip-address-list"><i class="fa fa-refresh"></i> Refresh IP addresses</button>
                                            </div>
                                            <div class="btn-group colvis-button-bar" id="button-bar-ip-address"></div>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <table class="display user_ip_table" id="user_ip_table-UID-${data['user_id']}" width="100%">
                                            <thead>
                                                <tr>
                                                    <th align="left" id="last_seen">Last Streamed</th>
                                                    <th align="left" id="first_seen">First Streamed</th>
                                                    <th align="left" id="ip_address">IP Address</th>
                                                    <th align="left" id="platform">Last Platform</th>
                                                    <th align="left" id="player">Last Player</th>
                                                    <th align="left" id="last_played">Last Played</th>
                                                    <th align="left" id="play_count">Play Count</th>
                                                </tr>
                                            </thead>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div role="tabpanel" class="tab-pane" id="tabs-tautullilogins">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class='table-card-header'>
                                        <div class="header-bar">
                                            <span>
                                                <i class="fa fa-sign-in"></i> Tautulli Login for <strong>
                                                    <span class="set-username">${data['friendly_name']}</span>
                                                </strong>
                                            </span>
                                        </div>
                                        <div class="button-bar">
                                            <div class="btn-group">
                                                <button class="btn btn-dark refresh-login-button" id="refresh-login-list"><i class="fa fa-refresh"></i> Refresh logins</button>
                                            </div>
                                            <div class="btn-group colvis-button-bar" id="button-bar-login"></div>
                                        </div>
                                    </div>
                                    <div class="table-card-back">
                                        <table class="display login_log_table" id="login_log_table-UID-${data['user_id']}" width="100%">
                                            <thead>
                                                <tr>
                                                    <th align="left" id="timestamp">Timestamp</th>
                                                    <th align="left" id="friendly_name">User</th>
                                                    <th align="left" id="user_group">User Group</th>
                                                    <th align="left" id="ip_address">IP Address</th>
                                                    <th align="left" id="host">Host</th>
                                                    <th align="left" id="os">Operating System</th>
                                                    <th align="left" id="browser">Browser</th>
                                                    <th align="left" id="expiry">Expiry</th>
                                                    <th align="left" id="login_success"></th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<footer></footer>
% else:
<div class="container-fluid">
    <div class="row">
        <div class="summary-container">
            <div class="summary-navbar">
                <div class="col-md-12">
                    <div class="summary-navbar-list">
                    </div>
                </div>
            </div>
            <div class="summary-content-wrapper">
                <div class='col-md-12'>
                    <div style="text-align: center; margin-top: 20px;">
                        <i class="fa fa-exclamation-triangle"></i> Error retrieving user information. Please see the logs for more details.
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
% endif
</%def>

<%def name="modalIncludes()">
<div id="edit-user-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="edit-user-modal">
</div>
<div class="modal fade" id="info-modal" tabindex="-1" role="dialog" aria-labelledby="info-modal">
</div>
<div class="modal fade" id="ip-info-modal" tabindex="-1" role="dialog" aria-labelledby="ip-info-modal">
</div>
<div class="modal fade" id="confirm-modal-delete" tabindex="-1" role="dialog" aria-labelledby="confirm-modal-delete">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-remove"></i></button>
                <h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
            </div>
            <div class="modal-body" style="text-align: center;">
                <p>Are you REALLY sure you want to delete <strong><span id="deleteCount"></span></strong> <span id="deleteType"></span> item(s)?</p>
                <p>This is permanent and cannot be undone!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-dark" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger btn-ok" data-dismiss="modal" id="confirm-delete">Delete</button>
            </div>
        </div>
    </div>
</div>
<div id="export-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="export-modal">
</div>
</%def>

<%def name="javascriptIncludes()">
<script src="${http_root}js/jquery.dataTables.min.js"></script>
<script src="${http_root}js/dataTables.colVis.js"></script>
<script src="${http_root}js/dataTables.bootstrap.min.js"></script>
<script src="${http_root}js/dataTables.bootstrap.pagination.js"></script>
% if data:
<script>
    % if str(data['user_id']).isdigit():
    var user_id = ${data['user_id']};
    % else:
    var user_id = null;
    % endif

    var username = '${data['username'].replace("'", "\\'")}';
</script>
<script src="${http_root}js/tables/history_table.js${cache_param}"></script>
<script src="${http_root}js/tables/playlists_table.js${cache_param}"></script>
<script src="${http_root}js/tables/export_table.js${cache_param}"></script>
<script src="${http_root}js/tables/user_ips.js${cache_param}"></script>
<script src="${http_root}js/tables/sync_table.js${cache_param}"></script>
<script src="${http_root}js/tables/login_logs.js${cache_param}"></script>
<script>
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        $.fn.dataTable.tables({ visible: true, api: true }).columns.adjust();
    });

    $(".inactive-user-tooltip").tooltip();

    function loadHistoryTable(media_type, transcode_decision) {
        // Build watch history table
        history_table_options.ajax = {
            url: 'get_history',
            type: 'POST',
            data: function ( d ) {
                return {
                    json_data: JSON.stringify( d ),
                    user_id: user_id,
                    media_type: media_type,
                    transcode_decision: transcode_decision
                };
            }
        };
        history_table = $('#history_table-UID-${data["user_id"]}').DataTable(history_table_options);
        history_table.column(2).visible(false);

        var colvis = new $.fn.dataTable.ColVis(history_table, { buttonText: '<i class="fa fa-columns"></i> Select columns', buttonClass: 'btn btn-dark', exclude: [0, 12] });
        $(colvis.button()).appendTo('#button-bar-history');

        clearSearchButton('history_table-UID-${data["user_id"]}', history_table);

        $('#media_type-selection').on('change', function () {
            $('#media_type-selection > label').removeClass('active');
            var selected_filter = $('input[name=media_type-filter]:checked', '#media_type-selection');
            $(selected_filter).closest('label').addClass('active');
            media_type = $(selected_filter).map(function () { return $(this).val(); }).get().join(',');
            setLocalStorage('user_' + user_id + '-history_media_type', media_type);
            history_table.draw();
        });

        $('#transcode_decision-selection').on('change', function () {
            $('#transcode_decision-selection > label').removeClass('active');
            var selected_filter = $('input[name=transcode_decision-filter]:checked', '#transcode_decision-selection');
            $(selected_filter).closest('label').addClass('active');
            transcode_decision = $(selected_filter).map(function () { return $(this).val(); }).get().join(',');
            setLocalStorage('user_' + user_id + 'history_transcode_decision', transcode_decision);
            history_table.draw();
        });
    }

    $('#nav-tabs-history').on('shown.bs.tab', function() {
        if (typeof(history_table) === 'undefined') {
            var media_type = getLocalStorage('user_' + user_id + '-history_media_type', 'all');
            $.each(media_type.split(','), function (i, item) {
                var history_media_type = $('#history-media_type-' + item);
                history_media_type.prop('checked', true);
                history_media_type.closest('label').addClass('active');
            });

            var transcode_decision = getLocalStorage('user_' + user_id + 'history_transcode_decision', 'all');
            $.each(transcode_decision.split(','), function (i, item) {
                var history_transcode_decision = $('#history-transcode_decision-' + item.replace(' ', '_'));
                history_transcode_decision.prop('checked', true);
                history_transcode_decision.closest('label').addClass('active');
            });

            loadHistoryTable(media_type, transcode_decision);
        }
    });

    $("#refresh-history-list").click(function () {
        history_table.draw();
    });

    function loadPlaylistsTable() {
        // Build playlists table
        playlists_table_options.ajax = {
            url: 'get_playlists_list',
            type: 'POST',
            data: function ( d ) {
                return {
                    json_data: JSON.stringify( d ),
                    user_id: user_id
                };
            }
        };
        playlists_table = $('#playlists_table-SID-${data["user_id"]}').DataTable(playlists_table_options);

        var colvis = new $.fn.dataTable.ColVis(playlists_table, { buttonText: '<i class="fa fa-columns"></i> Select columns', buttonClass: 'btn btn-dark' });
        $(colvis.button()).appendTo('#button-bar-playlists');

        clearSearchButton('playlists_table-SID-${data["user_id"]}', playlists_table);
    }

    $('#nav-tabs-playlists').on('shown.bs.tab', function() {
        if (typeof(playlists_table) === 'undefined') {
            loadPlaylistsTable();
        }
    });

    $("#refresh-playlists-table").click(function () {
        playlists_table.draw();
    });

    function loadSyncTable() {
        // Build user sync table
        sync_table_options.ajax = {
             url: 'get_sync?user_id=' + user_id,
            type: 'POST'
        };
        sync_table = $('#sync_table-UID-${data["user_id"]}').DataTable(sync_table_options);
        sync_table.column(2).visible(false);

        var colvis_sync = new $.fn.dataTable.ColVis( sync_table, { buttonText: '<i class="fa fa-columns"></i> Select columns', buttonClass: 'btn btn-dark', exclude: [0] } );
        $( colvis_sync.button() ).appendTo('#button-bar-sync');

        clearSearchButton('sync_table-UID-${data["user_id"]}', sync_table);
    }

    $("#refresh-syncs-list").click(function() {
        sync_table.ajax.reload();
    });

    function loadIPAddressTable() {
        // Build user IP table
        user_ip_table_options.ajax = {
            url: 'get_user_ips',
            type: 'POST',
            data: function ( d ) {
                return {
                    json_data: JSON.stringify( d ),
                    user_id: user_id
                };
            }
        };
        user_ip_table = $('#user_ip_table-UID-${data["user_id"]}').DataTable(user_ip_table_options);

        var colvis_user_ip = new $.fn.dataTable.ColVis( user_ip_table, { buttonText: '<i class="fa fa-columns"></i> Select columns', buttonClass: 'btn btn-dark'} );
        $( colvis_user_ip.button() ).appendTo('#button-bar-ip-address');

        clearSearchButton('user_ip_table-UID-${data["user_id"]}', user_ip_table);
    }

    $('#nav-tabs-ipaddresses').on('shown.bs.tab', function() {
        if (typeof(user_ip_table) === 'undefined') {
            loadIPAddressTable(user_id);
        }
    });

    $("#refresh-ip-address-list").click(function () {
        user_ip_table.draw();
    });

    function loadLoginTable() {
        // Build user login table
        login_log_table_options.ajax = {
            url: 'get_user_logins',
            type: 'POST',
            data: function(d) {
                return {
                    json_data: JSON.stringify(d),
                    user_id: user_id
                };
            }
        };
        login_log_table = $('#login_log_table-UID-${data["user_id"]}').DataTable(login_log_table_options);
        login_log_table.columns([1, 2]).visible(false);

        var colvis_login = new $.fn.dataTable.ColVis( login_log_table, { buttonText: '<i class="fa fa-columns"></i> Select columns', buttonClass: 'btn btn-dark', exclude: [7] } );
        $( colvis_login.button() ).appendTo('#button-bar-login');

        clearSearchButton('login_log_table-UID-${data["user_id"]}', login_log_table);
    }

    $('#nav-tabs-tautullilogins').on('shown.bs.tab', function() {
        if (typeof(login_log_table) === 'undefined') {
            loadLoginTable(user_id);
        }
    });

    $("#refresh-login-list").click(function () {
        login_log_table.draw();
    });

    function recentlyWatched() {
        // Populate recently watched
        $.ajax({
            url: 'get_user_recently_watched',
            async: true,
            data: {
                user_id: user_id,
                limit: 50
            },
            complete: function(xhr, status) {
                $("#user-recently-watched").html(xhr.responseText);
                highlightScrollerButton("#recently-watched");
                paginateScroller("#recently-watched", ".paginate-watched");
            }
        });
    }

    recentlyWatched();

    $(document).ready(function () {
        // Javascript to enable link to tab
        var hash = document.location.hash;
        var prefix = "tab_";
        if (hash) {
            $('.nav-list #nav-' + hash.replace('#' + prefix, "")).tab('show').trigger('show.bs.tab');
        }

        // Change hash for page-reload
        $('.nav-list a').on('shown.bs.tab', function (e) {
            window.location.hash = e.target.hash.replace("#", "#" + prefix);
        });

        // Populate watch time stats
        $.ajax({
            url: 'user_watch_time_stats',
            async: true,
            data: { user_id: user_id, user: username },
            complete: function(xhr, status) {
                $("#user-time-stats").html(xhr.responseText);
            }
        });

        // Populate platform stats
        $.ajax({
            url: 'user_player_stats',
            async: true,
            data: { user_id: user_id, user: username },
            complete: function(xhr, status) {
                $("#user-player-stats").html(xhr.responseText);
            }
        });

    });
</script>
% if _session['user_group'] == 'admin':
<script>
    function loadExportTable() {
        // Build export table
        export_table_options.ajax = {
            url: 'get_export_list',
            type: 'POST',
            data: function ( d ) {
                return {
                    json_data: JSON.stringify( d ),
                    user_id: user_id
                };
            }
        };
        export_table = $('#export_table-SID-${data["user_id"]}').DataTable(export_table_options);
        export_table.columns([2, 7]).visible(false);

        var colvis = new $.fn.dataTable.ColVis(export_table, { buttonText: '<i class="fa fa-columns"></i> Select columns', buttonClass: 'btn btn-dark' });
        $(colvis.button()).appendTo('#button-bar-export');

        clearSearchButton('export_table-SID-${data["user_id"]}', export_table);
    }

    $('#nav-tabs-export').on('shown.bs.tab', function() {
        if (typeof(export_table) === 'undefined') {
            loadExportTable();
        }
    });

    $("#refresh-export-table").click(function () {
        export_table.draw();
    });

    $("#edit-user-tooltip").tooltip();

    // Load edit user modal
    $("#toggle-edit-user-modal").click(function() {
        $("#edit-user-tooltip").tooltip('hide');
        $.ajax({
            url: 'edit_user_dialog',
            data: { user_id: user_id },
            cache: false,
            async: true,
            complete: function(xhr, status) {
                $("#edit-user-modal").html(xhr.responseText);
            }
        });
    });

    $(".export-button").click(function() {
        $.ajax({
            url: 'export_metadata_modal',
            data: {
                user_id: $(this).data('user_id'),
                media_type: $(this).data('media_type'),
                sub_media_type: $(this).data('sub_media_type'),
                export_type: $(this).data('export_type')
            },
            cache: false,
            async: true,
            complete: function(xhr, status) {
                $("#export-modal").html(xhr.responseText);
            }
        });
    });

    $('#row-edit-mode').on('click', function() {
        if ($(this).hasClass('active')) {
            $(this).tooltip('destroy');

            if (history_to_delete.length > 0) {
                $('#deleteCount').text(history_to_delete.length);
                $('#deleteType').text('history');
                $('#confirm-modal-delete').modal();
                $('#confirm-modal-delete').one('click', '#confirm-delete', function () {
                    $.ajax({
                        url: 'delete_history_rows',
                        type: 'POST',
                        data: { row_ids: history_to_delete.join(',') },
                        async: true,
                        success: function (data) {
                            var msg = "History deleted";
                            showMsg(msg, false, true, 2000);
                            history_table.draw();
                        }
                    });
                });
            }

            $('.history_table .delete-control').each(function () {
                $(this).addClass('hidden');
                $('#row-edit-mode-alert').fadeOut(200);
            });

        } else {
            $(this).tooltip({
                container: '.body-container',
                placement: 'bottom',
                title: 'Select rows to delete. Data is deleted upon exiting delete mode.',
                trigger: 'manual'
            }).tooltip('show');

            history_to_delete = [];
            $('.history_table .delete-control').each(function() {
                $(this).find('button.btn-danger').toggleClass('btn-warning').toggleClass('btn-danger');
                $(this).removeClass('hidden');
            });
        }
    });

    $('#sync-row-edit-mode').on('click', function() {
        if ($(this).hasClass('active')) {
            $(this).tooltip('destroy');

            if (syncs_to_delete.length > 0) {
                $('#deleteCount').text(syncs_to_delete.length);
                $('#deleteType').text('sync');
                $('#confirm-modal-delete').modal();
                $('#confirm-modal-delete').one('click', '#confirm-delete', function () {
                    syncs_to_delete.forEach(function(row, idx) {
                        $.ajax({
                            url: 'delete_sync_rows',
                            type: 'POST',
                            data: {
                                client_id: row.client_id,
                                sync_id: row.sync_id
                            },
                            async: true,
                            success: function (data) {
                                var msg = "Sync deleted";
                                showMsg(msg, false, true, 2000);
                            }
                        });
                    });
                    sync_table.ajax.reload();
                });
            }

            $('.sync_table .delete-control').each(function () {
                $(this).addClass('hidden');
                $('#sync-row-edit-mode-alert').fadeOut(200);
            });

        } else {
            $(this).tooltip({
                container: '.body-container',
                placement: 'bottom',
                title: 'Select syncs to delete. Data is deleted upon exiting delete mode.',
                trigger: 'manual'
            }).tooltip('show');

            syncs_to_delete = [];
            $('.sync_table .delete-control').each(function() {
                $(this).find('button.btn-danger').toggleClass('btn-warning').toggleClass('btn-danger');
                $(this).removeClass('hidden');
            });
        }
    });
</script>
% endif
% endif
</%def>